package server;

import interfaces.Order;
import interfaces.Product;

import java.rmi.RemoteException;
import java.util.HashMap;
import javax.rmi.PortableRemoteObject;

public class OrderImpl extends PortableRemoteObject implements Order {
	private int id = 0;
	private HashMap<Product, Double> products = null;

	/**
	 * Constructor
	 * @param newId		The order id
	 * @throws RemoteException
	 */
	public OrderImpl( int newId ) throws RemoteException {
		super();

		id = newId;
		products = new HashMap<Product, Double>();
	}

	/**
	 * Returns the Order id
	 * 
	 * @return
	 * @throws RemoteException
	 */
	public int getId() {
		return id;
	}

	/**
	 * Adds a Product to the products list
	 * 
	 * @param product	Product to be added
	 * @param amount
	 * @throws RemoteException
	 */
	public void add( Product product, double amount ) {
		if( productExists( product ) ) {
			products.put( product, ( products.get( product ) + amount ) );
		} else {
			products.put( product, amount );
		}
	}

	/**
	 * Returns True if the specified Product exists in the product list
	 * 
	 * @param product	Product
	 * @return
	 * @throws RemoteException
	 */
	public boolean productExists( Product product ) {
		return products.get( product ) != null;
	}

	/**
	 * Removes a Product from the products list
	 * 
	 * @param product	Product to be removed
	 * @throws RemoteException
	 */
	public void remove( Product product ) {

		if( products.get( product ) !=null )
		{
			if( (products.get( product ) > 1) ) {
				products.put( product, ( products.get( product ) - 1.0 ) );
			} else {
				products.remove( product );
			}
		}
	}

	/**
	 * Returns the products list
	 * 
	 * @return
	 * @throws RemoteException
	 */
	public HashMap<Product, Double> getProducts() {
		return products;
	}

	/**
	 * Returns the total price for the Order
	 * 
	 * @return
	 * @throws RemoteException
	 */
	public double getTotal() {
		double total = 0.00;

		try {
			for( Product product: products.keySet() ) {
				total += product.getPrice() * products.get( product );
			}
		} catch( RemoteException e ) {
			e.printStackTrace();
		}

		return total;
	}
}
